package com.devilvan.betrice.recruitment.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.devilvan.betrice.recruitment.mapper.BossSkillMapper;
import com.devilvan.betrice.recruitment.po.BossSkillPo;
import com.devilvan.betrice.recruitment.repository.BossSkillRepository;
import com.devilvan.betrice.recruitment.service.BossSkillService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Evad.Wu
 * @Description Boss直聘 招聘信息-技能信息 业务逻辑类
 * @date 2022-08-08
 */
@Service
public class BossSkillServiceImpl extends ServiceImpl<BossSkillMapper, BossSkillPo> implements BossSkillService {
    @Resource(name = "bossSkillRepository")
    private BossSkillRepository bossSkillRepository;

    @Override
    public Set<BossSkillPo> checkSaveSkills(Set<String> skills) {
        Set<BossSkillPo> bossSkillPoSet = new HashSet<>();
        Set<BossSkillPo> skillPoSet = Optional.of(skills).map(m -> {
            Set<BossSkillPo> set = null;
            if (!m.isEmpty()) {
                set = this.findBySkillIn(m);
            }
            return set;
        }).orElseGet(HashSet::new);
        if (skillPoSet.isEmpty()) {
            bossSkillPoSet = skills.stream().map(m -> new BossSkillPo(m.trim())).collect(Collectors.toSet());
        } else {
            Set<String> skillSet = skillPoSet.stream().map(BossSkillPo::getSkill).collect(Collectors.toSet());
            Collection<String> intersection = CollUtil.disjunction(skills, skillSet);
            if (!intersection.isEmpty()) {
                bossSkillPoSet = intersection.stream().map(m -> new BossSkillPo(m.trim())).collect(Collectors.toSet());
                skillPoSet.addAll(bossSkillPoSet);
            }
        }
        bossSkillRepository.saveAllAndFlush(bossSkillPoSet);
        return skillPoSet;
    }


    @Override
    public Set<BossSkillPo> findBySkillIn(Set<String> skills) {
        LambdaQueryWrapper<BossSkillPo> queryWrapper = new QueryWrapper<BossSkillPo>().lambda();
        queryWrapper.in(BossSkillPo::getSkill, skills);
        queryWrapper.groupBy(BossSkillPo::getSkill);
        return new HashSet<>(this.list(queryWrapper));
    }
}
